package com.zm.spring.jdbc;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class BasicServlet extends HttpServlet {

	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//首先可以来得到资源路径
		String uri = req.getRequestURI();
		String path = uri.substring(uri.lastIndexOf("/")+1);
		System.out.println(uri+"-"+path);
		
//		req.setCharacterEncoding("UTF-8");
//		resp.setCharacterEncoding("UTF-8");
		
		//获取当前servlet中的所以方法
		Method[] methods = this.getClass().getDeclaredMethods();
		for(Method m : methods) {
//			System.out.println(m.getName());
			if(m.getName().equals(path)) {
				
				try {
					m.invoke(this,req,resp);
				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					e.printStackTrace();
				}
				return;
			}
		}
		
	}

	protected void send(HttpServletResponse resp,int obj) throws ServletException, IOException {
		try {
			PrintWriter out = resp.getWriter();
			out.print(obj);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void send(HttpServletResponse resp,String obj) throws ServletException, IOException {
		try {
			PrintWriter out = resp.getWriter();
			out.print(obj);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void send(HttpServletResponse resp,Object obj) throws ServletException, IOException {
		try {
			PrintWriter out = resp.getWriter();
			Gson gson = new Gson();
			String json = gson.toJson(obj);
			out.print(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
